package com.fjec.gateway.filter.wrapper;

import com.google.common.base.Strings;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

public class RedirectResponseWrapper extends HttpServletResponseWrapper {

    private HttpServletRequest request;

    public RedirectResponseWrapper(HttpServletRequest request, HttpServletResponse response) {
        super(response);
        this.request = request;
    }

    @Override
    public void sendRedirect(String location) throws IOException {
        if (Strings.isNullOrEmpty(location)) {
            super.sendRedirect(location);
            return;
        }
        try {
            final URI uri = new URI(location);
            if (uri.getScheme() != null) {
                super.sendRedirect(location);
                return;
            }
        } catch (URISyntaxException ex) {
            super.sendRedirect(location);
        }
        // !!! FIX Scheme  !!!
        String finalUrl = "https://" + this.request.getServerName();
        if (request.getServerPort() != 80 && request.getServerPort() != 443) {
            finalUrl += ":" + request.getServerPort();
        }
        finalUrl += location;
        super.sendRedirect(finalUrl);
    }
}
